package com.jeesit.cloud.spot.web.api_controller.hedging_scheme_inst;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeesit.cloud.annotation.ModuleLog;
import com.jeesit.cloud.dto.LogInfo;
import com.jeesit.cloud.dto.MaterialProductDto;
import com.jeesit.cloud.spot.service.IHedgingSchemeInstService;
import com.jeesit.cloud.spot.service.IMaterialProductService;
import com.jeesit.cloud.verify.UserAuthDetail;
import com.jeesit.cloud.constants.LogConstant;
import com.jeesit.cloud.util.ExportExcel;
import com.jeesit.cloud.dto.HedgingSchemeInstDto;
import com.jeesit.cloud.validate.UpdateAction;
import com.jeesit.cloud.validate.CreateAction;
import com.jeesit.cloud.validate.QueryAction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.jeesit.cloud.model.*;

import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeesit.cloud.dto.JSONResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 *   相关接口
 *　　
 *   @description HedgingSchemeInst 接口
 *   ---------------------------------
 *   @author lss
 *   @date 2024-01-25
 */
@Slf4j
@RestController
@RequestMapping("/api/auth/v1/hedging_scheme_inst")
@Api(tags = {"套保方案合约明细"})
public class HedgingSchemeInstController {

    @Autowired
    private IHedgingSchemeInstService hedgingSchemeInstService;

    @Autowired
    private IMaterialProductService materialProductService;

    /**
     * @description 获取分页列表
     * ---------------------------------
     * @author lss
     * @date 2024-01-25
     */
    @ApiOperation("获取分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "pageNo", value = "页码", dataTypeClass = Integer.class , paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页行数，最少10条，最多100条", dataTypeClass = Integer.class , paramType = "query", required = true)
    })
    @PostMapping(value = "/hedging_scheme_inst_page")
    public JSONResult<Page<HedgingSchemeInst>> getHedgingSchemeInstPage(Authentication authentication,@Validated(QueryAction.class)HedgingSchemeInstDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        Page<HedgingSchemeInst> page=new Page<HedgingSchemeInst>(dto.getPageNo(), dto.getPageSize());
        hedgingSchemeInstService.page(page,dto);
        JSONResult<Page<HedgingSchemeInst>> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setData(page);
        return res;
    }

/**
     * @description 获取列表
     * ---------------------------------
     * @author lss
     * @date 2024-01-25
     */
    @ApiOperation("获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "size", value = "查询数量，最多查询1000条", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @PostMapping(value = "/hedging_scheme_inst_list")
    public JSONResult<HedgingSchemeInst> getHedgingSchemeInstList(Authentication authentication, @Validated(QueryAction.class)HedgingSchemeInstDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<HedgingSchemeInst> list = hedgingSchemeInstService.list(dto.getSize(),dto);
        JSONResult<HedgingSchemeInst> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setDatas(list);
        return res;
    }

    @ApiOperation("查询品类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "size", value = "查询数量，最多查询1000条", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @PostMapping(value = "/hedging_catalog_list")
    public JSONResult<HedgingSchemeInstDto> getCatalogList(Authentication authentication, String[] instrumentCode, String[] product
            , Integer[] direction, Integer[] maxPosition, Integer[] positionType, Integer[] priceType,
           Double[] maxPrice, Double[] minPrice, Integer[] volumeMultiple, Double[] maximumOpenWeight, Long[] instrumentUuid){
        List<HedgingSchemeInstDto> list = new ArrayList<>();
        for(int i=0;i<instrumentUuid.length;i++ ){
            HedgingSchemeInstDto it = new HedgingSchemeInstDto();
            it.setInstrumentUuid(instrumentUuid[i]);
            it.setDirection(direction[i]);
            it.setMaxPosition(maxPosition[i]);
            it.setPositionType(positionType[i]);
            it.setInstrumentCode(instrumentCode[i]);
            it.setMaxPrice(maxPrice==null?0:maxPrice[i]);
            it.setMinPrice(minPrice==null?0:minPrice[i]);
            it.setPriceType(priceType[i]);
            it.setProduct(product[i]);
            it.setVolumeMultiple(volumeMultiple[i]);
          it.setMaximumOpenWeight(maximumOpenWeight[i]);
           MaterialProductDto materialProductDto = new MaterialProductDto();
           materialProductDto.setProducts(it.getProduct());
           materialProductService.list(1,materialProductDto);
           it.setCatalogName(materialProductService.list(1,materialProductDto).get(0).getCatalogName());
            list.add(it);
       }
        JSONResult<HedgingSchemeInstDto> res = new JSONResult<>();
        res.setMessage("查询成功");
        res.setSuccess(true);
        res.setDatas(list);
        return res;
    }


    /**
     * @description 导出列表
     * ---------------------------------
     * @author lss
     * @date 2024-01-25
     */
    @ApiOperation("导出列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('HedgingSchemeInst_Export','SUPER_ADMIN')")
    @PostMapping(value = "/hedging_scheme_inst_export")
    public void export(HttpServletResponse response,Authentication authentication, @Validated(QueryAction.class)HedgingSchemeInstDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<HedgingSchemeInst> datas = hedgingSchemeInstService.list(0,dto);
        String[] header = new String[]{"合约代码","合约uuid","品种名称","品种uuid","建仓方向","最大手数","手数类型 0持仓量 1开仓量","最大价格","最小价格","价格设置 0区间价 1市价 2指定价","指定价格","套保方案uuid","创建人姓名","创建时间","创建人uuid","",""};
        List<List<Object>> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("0.00");
        for(HedgingSchemeInst it : datas){
            List<Object> data = new ArrayList<>();
            data.add(it.getInstrumentCode());
            data.add(it.getInstrumentUuid());
            data.add(it.getProductName());
            data.add(it.getProductUuid());
            data.add(it.getDirection());
            data.add(it.getMaxPosition());
            data.add(it.getPositionType());
            data.add(Optional.ofNullable(it.getMaxPrice()).map(s->df.format(s)).orElse(""));
            data.add(Optional.ofNullable(it.getMinPrice()).map(s->df.format(s)).orElse(""));
            data.add(it.getPriceType());
            data.add(Optional.ofNullable(it.getPrice()).map(s->df.format(s)).orElse(""));
            data.add(it.getSchemeUuid());
            data.add(it.getAddUserName());
            data.add(Optional.ofNullable(it.getAddTime()).map(s->sdf.format(s)).orElse(""));
            data.add(it.getAddUserUuid());
            data.add(it.getDeleted());
            list.add(data);
        }
        ExportExcel excel = new ExportExcel();
        excel.setName("");
        excel.exportToExcel(response,header,list,0);
    }

    /**
     * @description 新建
     *
     * @author lss
     * @date 2024-01-25
     */
    @ApiOperation("新建")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('HedgingSchemeInst_Add','SUPER_ADMIN')")
    @ModuleLog("HedgingSchemeInst")
    @PostMapping("/hedging_scheme_inst_add")
    public JSONResult<HedgingSchemeInst> saveNewEntity(HttpServletRequest request,Authentication authentication, @Validated(CreateAction.class) HedgingSchemeInstDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<HedgingSchemeInst> res= saveData(user,null,entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "保存，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    /**
     * @description 更新
     *
     * @author lss
     * @date 2024-01-25
     */
    @ApiOperation("更新 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('HedgingSchemeInst_Modify','SUPER_ADMIN')")
    @ModuleLog("HedgingSchemeInst")
    @PostMapping("/hedging_scheme_inst_edit")
    public JSONResult<HedgingSchemeInst> saveEditEntity(HttpServletRequest request,Authentication authentication,@Validated(UpdateAction.class) HedgingSchemeInstDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<HedgingSchemeInst> res= saveData(user,entity.getUuid(),entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "更新，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    private JSONResult<HedgingSchemeInst> saveData(User user,Long id,HedgingSchemeInstDto entity){
        JSONResult<HedgingSchemeInst> res = new JSONResult<>();
        HedgingSchemeInst it = new HedgingSchemeInst();
        if(id==null){
            it.setDeleted(false);
        } else {
            it = hedgingSchemeInstService.getById(entity.getUuid());
        }
        it.setInstrumentCode(entity.getInstrumentCode());
        it.setInstrumentUuid(entity.getInstrumentUuid());
        it.setProductName(entity.getProductName());
        it.setProductUuid(entity.getProductUuid());
        it.setDirection(entity.getDirection());
        it.setMaxPosition(entity.getMaxPosition());
        it.setPositionType(entity.getPositionType());
        it.setMaxPrice(entity.getMaxPrice());
        it.setMinPrice(entity.getMinPrice());
        it.setPriceType(entity.getPriceType());
        it.setPrice(entity.getPrice());
        it.setSchemeUuid(entity.getSchemeUuid());
        it.setAddUserName(entity.getAddUserName());
        it.setAddUserUuid(entity.getAddUserUuid());
        hedgingSchemeInstService.saveOrUpdate(it);
        res.setData(it);
        res.setSuccess(true);
        res.setMessage("保存成功");
        return res;
    }


    /**
     * @description 删除
     *
     * @author lss
     * @date 2024-01-25
     */
    @ApiOperation("删除")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
        @ApiImplicitParam(name = "ids", value = "删除id（支持批量删除）", dataTypeClass = Long.class , allowMultiple = true,paramType = "query", required = true),
    })
    @PreAuthorize("hasAnyAuthority('HedgingSchemeInst_Remove','SUPER_ADMIN')")
    @ModuleLog("HedgingSchemeInst")
    @PostMapping("hedging_scheme_inst_del")
        public JSONResult<Void> delEntity(HttpServletRequest request,Authentication authentication,@Size(min=1,max=50,message = "请选择要删除数据") Long[] ids) throws Exception{
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<Void> res = new JSONResult<>();
        for(int i=0;i<ids.length;i++){
            HedgingSchemeInst it = hedgingSchemeInstService.getById(ids[i]);
            hedgingSchemeInstService.removeById(it.getUuid());
        }
        request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "删除，数据ID:" + StringUtils.join(ids)));
        res.setMessage("删除成功");
        res.setSuccess(true);
        return res;
    }

}

